﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for LaporanPembelianForm.xaml
    /// </summary>
    /// 
    public struct pembelian
    {
        public string nama_barang;
        public string jumlah;
    };

    public partial class LaporanPembelianForm : Window
    {
        private bool isChoose = false;
        private int state = 0;
        private string ID1, ID2;
        private bool isUbah = false;
        private DataSet ubah = new DataSet();

        List<pembelian> arry = new List<pembelian>();

        public LaporanPembelianForm()
        {
            InitializeComponent();
        }

        public LaporanPembelianForm(string ID1, string ID2)
        {
            this.ID1 = ID1;
            this.ID2 = ID2;
            isUbah = true;
            InitializeComponent();
            label1.Content = "Ubah Pembelian";
            addButton.Content = "Edit";
            cancelButton.Content = "Cancel";
        }

        public void InitData()
        {
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                homeWindow.Con.Open();

                SqlDataAdapter da = new SqlDataAdapter("select nama_barang from daftar_barang", homeWindow.Con);
                DataSet ds = new DataSet();
                da.Fill(ds, "Daftar Penyewaan");

                int count = ds.Tables["Daftar Penyewaan"].Rows.Count + 1;

                for (int i = 0; i < count - 1; i++)
                {
                    namaBox.Items.Add(ds.Tables["Daftar Penyewaan"].Rows[i].ItemArray.ElementAt(0).ToString());
                }

                if (!isUbah)
                {
                    prevButton.IsEnabled = false;
                    nextButton.IsEnabled = false;
                }
                else
                {
                    da = new SqlDataAdapter("select nama_barang , a.jumlah , b.keterangan from (pembelian as a inner join laporan_barang as b on a.ID_Laporan = b.ID_Laporan) inner join daftar_barang as d on a.ID_Barang = d.ID_Barang where a.ID_Laporan = '" + ID1 + "' and a.ID_Barang = '" + ID2 + "';", homeWindow.Con);
                    ubah = new DataSet();
                    da.Fill(ubah, "Daftar Pembelian");
                    namaBox.SelectedItem = ubah.Tables["Daftar Pembelian"].Rows[0].ItemArray.ElementAt(0).ToString();
                    jumlahText.Text = ubah.Tables["Daftar Pembelian"].Rows[0].ItemArray.ElementAt(1).ToString();
                    keteranganText.Text = ubah.Tables["Daftar Pembelian"].Rows[0].ItemArray.ElementAt(2).ToString();
                    prevButton.Visibility = System.Windows.Visibility.Collapsed;
                    nextButton.Visibility = System.Windows.Visibility.Collapsed;
                    keteranganText.IsReadOnly = true;
                }
                homeWindow.Con.Close();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
            }
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                if (!isUbah)
                {
                    state++;
                    pembelian pem;
                    pem.nama_barang = namaBox.SelectedItem.ToString();
                    pem.jumlah = jumlahText.Text;
                    if (state - 1 == arry.Count)
                        arry.Add(pem);
                    else
                    {
                        arry.RemoveAt(state - 1);
                        arry.Insert(state - 1, pem);
                    }
                    if (state == arry.Count)
                    {
                        nextButton.IsEnabled = false;
                        namaBox.SelectedIndex = -1;
                        jumlahText.Text = "0";
                        isChoose = false;
                        nextButton.IsEnabled = false;
                    }
                    else
                    {
                        namaBox.SelectedItem = arry.ElementAt(state).nama_barang;
                        jumlahText.Text = arry.ElementAt(state).jumlah;
                        isChoose = false;
                        nextButton.IsEnabled = true;
                    }
                    prevButton.IsEnabled = true;

                    try
                    {
                        homeWindow.Con.Open();

                        SqlDataAdapter da = new SqlDataAdapter("select nama_barang,total,ID_barang from daftar_barang", homeWindow.Con);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Daftar Barang");

                        da = new SqlDataAdapter("select * from laporan_barang order by ID_Laporan", homeWindow.Con);
                        DataSet ds1 = new DataSet();
                        da.Fill(ds1, "Daftar Pembelian");

                        string _Insertss = @"insert into laporan_barang (ID_Laporan,Tanggal,Keterangan,username)
                                  values ('L" + "','" + DateTime.Now.ToString("M/d/yyyy") + "','" + keteranganText.Text + "','" + topWindow.username + "');";
                        SqlCommand _cmdss = new SqlCommand(_Insertss, homeWindow.Con);
                        // Execute the command
                        _cmdss.ExecuteNonQuery();

                        da = new SqlDataAdapter("select IDENT_CURRENT('laporan_barang')", homeWindow.Con);
                        DataSet dd = new DataSet();
                        da.Fill(dd, "Laporan");

                        Console.WriteLine(dd.Tables["Laporan"].Rows[0].ItemArray.ElementAt(0).ToString());

                        for (int i = 0; i < arry.Count; i++)
                        {
                            int tempsum = Int32.Parse(arry.ElementAt(i).jumlah);
                            string s = "";
                            for (int j = 0; j < ds.Tables["Daftar Barang"].Rows.Count; j++)
                            {
                                if (arry.ElementAt(i).nama_barang.Equals(ds.Tables["Daftar Barang"].Rows[j].ItemArray.ElementAt(0).ToString()))
                                {
                                    s += ds.Tables["Daftar Barang"].Rows[j].ItemArray.ElementAt(2).ToString();
                                }
                            }

                            string _Inserts = @"insert into pembelian (ID_barang, ID_Laporan, Jumlah)
                                  values ('" + s + "','" + "L" + addNol(Int32.Parse(dd.Tables["Laporan"].Rows[0].ItemArray.ElementAt(0).ToString())) + dd.Tables["Laporan"].Rows[0].ItemArray.ElementAt(0).ToString() + "','" + tempsum + "');";
                            SqlCommand _cmds = new SqlCommand(_Inserts, homeWindow.Con);
                            // Execute the command
                            _cmds.ExecuteNonQuery();

                            for (int j = 0; j < ds.Tables["Daftar Barang"].Rows.Count; j++)
                            {
                                if (arry.ElementAt(i).nama_barang.Equals(ds.Tables["Daftar Barang"].Rows[j].ItemArray.ElementAt(0).ToString()))
                                {
                                    tempsum += Int32.Parse(ds.Tables["Daftar Barang"].Rows[j].ItemArray.ElementAt(1).ToString());
                                }
                            }

                            string _Insert = @"update daftar_barang
                                  set total = " + tempsum + " where nama_barang = \'" + arry.ElementAt(i).nama_barang + "\';";
                            SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                            // Execute the command
                            _cmd.ExecuteNonQuery();
                        }
                        MessageBox.Show("Penambahan " + arry.Count + " informasi laporan pembelian baru berhasil", "New Report");
                        homeWindow.Con.Close();
                    }
                    catch (SqlException sqle)
                    {
                        MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                    }
                    homeWindow.top.refresh();
                    restart();
                }
                else
                {
                    try
                    {
                        homeWindow.Con.Open();

                        SqlDataAdapter da = new SqlDataAdapter("select ID_barang,Total from daftar_barang where nama_barang = '" + namaBox.SelectedItem.ToString() + "'", homeWindow.Con);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Daftar Barang");

                        int news = Int32.Parse(jumlahText.Text) - Int32.Parse(ubah.Tables["Daftar Pembelian"].Rows[0].ItemArray.ElementAt(1).ToString());

                        string _Insert = @"update Pembelian
                                        set ID_Barang = '" + ds.Tables["Daftar Barang"].Rows[0].ItemArray.ElementAt(0).ToString() + "', Jumlah = '" + jumlahText.Text +
                                                "' where ID_Laporan = '" + ID1 + "';";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        _Insert = @"update Laporan_Barang
                                        set username = '" + topWindow.username + "' where ID_Laporan = '" + ID1 + "';";

                        _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        news = news + Int32.Parse(ds.Tables["Daftar Barang"].Rows[0].ItemArray.ElementAt(1).ToString());

                        _Insert = @"update daftar_barang
                                        set Total = '" + news +
                                                "' where ID_Barang = '" + ds.Tables["Daftar Barang"].Rows[0].ItemArray.ElementAt(0).ToString() + "';";
                        _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();
                        MessageBox.Show("Pengubahan berhasil dilakukan", "Edit Pembelian");
                        homeWindow.Con.Close();
                    }
                    catch (SqlException sqle)
                    {
                        MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                    }
                    homeWindow.top.refresh();
                    homeWindow.top.Focus();
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("Ada kesalahan pengisian informasi laporan pembelian", "Invalid Information");
            }
        }

        private void restart()
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            arry.Clear();
            state = 0;
            keteranganText.Text = "";
            jumlahText.Text = "0";
            keteranganText.Background = validColor;
            namaBox.Background = validColor;
            jumlahText.Background = validColor;
            prevButton.IsEnabled = false;
            nextButton.IsEnabled = false;
        }

        private Boolean errorChecking()
        {
            Boolean valid = true;
            Brush invalidColor = new SolidColorBrush(Color.FromRgb(255, 225, 0));
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            int temp;
            if (namaBox.SelectedIndex == -1)
            {
                namaBox.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                namaBox.Background = validColor;
            }
            if (jumlahText.Text == "" || Int32.Parse(jumlahText.Text) < 1 || !Int32.TryParse(jumlahText.Text.ToString(), out temp))
            {
                jumlahText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                jumlahText.Background = validColor;
            }
            return valid;
        }


        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                homeWindow.top.Focus();
                this.Close();
            }
            else
            {
                restart();
            }
        }

        private void nextButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                state++;
                pembelian pem;
                pem.nama_barang = namaBox.SelectedItem.ToString();
                pem.jumlah = jumlahText.Text;
                if (state - 1 == arry.Count)
                    arry.Add(pem);
                else
                {
                    arry.RemoveAt(state - 1);
                    arry.Insert(state - 1, pem);
                }
                if (state == arry.Count)
                {
                    nextButton.IsEnabled = false;
                    namaBox.SelectedIndex = -1;
                    jumlahText.Text = "0";
                    isChoose = false;
                    nextButton.IsEnabled = false;
                }
                else
                {
                    namaBox.SelectedItem = arry.ElementAt(state).nama_barang;
                    jumlahText.Text = arry.ElementAt(state).jumlah;
                    isChoose = false;
                    nextButton.IsEnabled = true;
                }
                prevButton.IsEnabled = true;
            }
            else
            {
                MessageBox.Show("Ada kesalahan pengisian informasi laporan pembelian", "Invalid Information");
            }
        }

        private void prevButton_Click(object sender, RoutedEventArgs e)
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200, 200, 200));
            keteranganText.Background = validColor;
            namaBox.Background = validColor;
            jumlahText.Background = validColor;
            state--;
            pembelian pem;
            if (isChoose != false)
            {
                pem.nama_barang = namaBox.SelectedItem.ToString();
                pem.jumlah = jumlahText.Text;
                if (state + 1 == arry.Count)
                    arry.Add(pem);
                else
                {
                    arry.RemoveAt(state);
                    arry.Insert(state, pem);
                }
            }
            if (state == 0)
            {
                prevButton.IsEnabled = false;

            }
            else
            {
                prevButton.IsEnabled = true;
            }
            namaBox.SelectedItem = arry.ElementAt(state).nama_barang;
            jumlahText.Text = arry.ElementAt(state).jumlah;
            isChoose = false;
            nextButton.IsEnabled = true;
        }

        private void jumlahText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!isChoose)
                isChoose = true;
            else
            {
                if (jumlahText.Text.Count() > 0)
                    nextButton.IsEnabled = true;
                else
                    nextButton.IsEnabled = false;
            }
        }

        private void jumlahText_MouseUp(object sender, MouseButtonEventArgs e)
        {
            jumlahText.Text = "";
        }

        private void namaBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isChoose)
                isChoose = true;
        }

        private void formPembelianWindow_Closed(object sender, EventArgs e)
        {
            homeWindow.top.refresh();
            homeWindow.top.Focus();
        }

        private string addNol(int x)
        {
            string temp = "";
            string angka = x.ToString();

            if (angka.Count() == 4)
            {
                temp = "0";
            }
            else if (angka.Count() == 3)
            {
                temp = "00";
            }
            else if (angka.Count() == 2)
            {
                temp = "000";
            }
            else if (angka.Count() == 1)
            {
                temp = "0000";
            }
            Console.WriteLine(temp);
            return temp;
        }
    }
}
